<template>
  <div class="signature-manage-container">
    <el-card class="signature-card">
      <div class="card-header">
        <h3 class="card-title">签名管理</h3>
        <p class="card-subtitle">管理PDF报告中的检验和审核人员签名（SVG格式）</p>
      </div>

      <!-- 检验人员签名 -->
      <div class="signature-section">
                 <div class="section-header">
           <h4 class="section-title">检验人员签名</h4>
           <span class="section-desc">
                   当前用户：{{ currentUsername }} ({{ 
        currentUserRole === 'superadmin' ? '超级管理员' : 
        currentUserRole === 'admin' ? '管理员' : '普通用户' 
      }})
      <br v-if="currentUserRole === 'admin' || currentUserRole === 'superadmin'">
      <span v-if="currentUserRole === 'admin' || currentUserRole === 'superadmin'" style="color: #409EFF;">检验人员：{{ signatureSettings.inspectorName }}</span>
           </span>
         </div>
        
        <div class="signature-content">
          <div class="signature-preview">
            <div class="preview-label">当前签名：</div>
            <div class="signature-container" @contextmenu.prevent @selectstart.prevent>
              <div v-if="inspectorSignature" class="signature-svg-container">
                <div v-html="inspectorSignature" class="signature-svg"></div>
              </div>
              <div v-else class="no-signature">暂无签名</div>
            </div>
          </div>
          
          <div class="signature-actions">
                         <div class="inspector-info">
               <p><strong>检验人员：</strong>{{ signatureSettings.inspectorName }}</p>
               <p><strong>签名类型：</strong>文本签名（自动生成）</p>
               <p><strong>说明：</strong>检验人员签名根据用户角色自动分配，无需手动设置</p>
             </div>
            
                         <div class="inspector-actions">
               <el-button type="info" @click="refreshInspectorSignature">
                 重新分配检验人员
               </el-button>
             </div>
          </div>
        </div>
      </div>

      <!-- 审核人员签名 -->
      <div class="signature-section">
        <div class="section-header">
          <h4 class="section-title">审核人员签名</h4>
          <span class="section-desc">预设审核人员：姚俊磊</span>
        </div>
        
        <div class="signature-content">
          <div class="signature-preview">
            <div class="preview-label">当前签名：</div>
                         <div class="signature-container" @contextmenu.prevent @selectstart.prevent>
                             <div class="signature-display-area">
                <div class="signature-label">审核：</div>
                <div class="signature-content-area">
                  <div v-if="reviewerSignature" class="signature-svg-container">
                    <div v-html="reviewerSignature" class="signature-svg"></div>
                  </div>
                  <div v-else class="no-signature">暂无签名</div>
                </div>
              </div>
             </div>
          </div>
          
          <div class="signature-actions">
            <div class="svg-input-section">
              <el-input
                v-model="reviewerSvgInput"
                type="textarea"
                :rows="8"
                placeholder="请输入SVG代码，例如：&#60;svg width='200' height='60' xmlns='http://www.w3.org/2000/svg'&#62;&#60;path d='M10 30 Q50 10 90 30 T170 30' stroke='black' stroke-width='2' fill='none'&#62;&#60;/path&#62;&#60;text x='10' y='50' font-family='Arial' font-size='14'&#62;姚俊磊&#60;/text&#62;&#60;/svg&#62;"
                class="svg-textarea"
              />
              <div class="svg-actions">
                <el-button type="primary" @click="saveReviewerSvg" :disabled="!reviewerSvgInput.trim()">
                  保存SVG签名
                </el-button>
                <el-button @click="clearReviewerSvg">
                  清空
                </el-button>
                <el-button type="info" @click="generateReviewerExample">
                  生成示例
                </el-button>
              </div>
            </div>
            
            <el-button 
              v-if="reviewerSignature" 
              type="danger" 
              size="large"
              @click="removeReviewerSignature"
              style="margin-top: 10px;"
            >
              删除签名
            </el-button>
          </div>
        </div>
      </div>


    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

// 签名存储键
const SIGNATURE_STORAGE_KEY = 'pdf_signatures'
const SETTINGS_STORAGE_KEY = 'pdf_signature_settings'

// 当前用户信息
const currentUsername = ref(localStorage.getItem('currentUsername') || '未知用户')

// 尝试从多个可能的键名获取用户角色（优先使用userRole）
const userRoleFromStorage = localStorage.getItem('userRole') || 
                           localStorage.getItem('currentUserRole') || 
                           localStorage.getItem('role') || 
                           'user'
const currentUserRole = ref(userRoleFromStorage)

// 预设检验人员列表（普通用户的用户名）
const presetInspectors = ['葛岑茹', '葛爽', '李秋月', '张小娟', '杨雅静', '朱萍萍', '蔡艳花', '甄利蕊', '赵金蓉']

// 签名数据
const inspectorSignature = ref('')
const reviewerSignature = ref('')

// SVG输入
const reviewerSvgInput = ref('')

// 获取检验人员姓名
function getInspectorName() {
      if (currentUserRole.value === 'admin' || currentUserRole.value === 'superadmin') {
    // 管理员登录时，随机选择一个预设检验人员（普通用户）
    const randomIndex = Math.floor(Math.random() * presetInspectors.length)
    return presetInspectors[randomIndex]
  } else {
    // 普通用户登录时，使用当前用户名
    return currentUsername.value
  }
}

// 重新分配检验人员（只从预设列表中分配，不分配管理员）
function getRandomInspectorName() {
  // 只从预设的普通用户列表中选择，不分配管理员
  const randomIndex = Math.floor(Math.random() * presetInspectors.length)
  return presetInspectors[randomIndex]
}

// 签名设置
const signatureSettings = ref({
  inspectorName: getInspectorName(),
  reviewerName: '姚俊磊'
})

// 隐私保护功能
function setupPrivacyProtection() {
  // 禁用右键菜单
  document.addEventListener('contextmenu', (e) => {
    if (e.target.closest('.signature-container')) {
      e.preventDefault()
      ElMessage.warning('签名受保护，禁止右键操作')
      return false
    }
  })

  // 禁用拖拽
  document.addEventListener('dragstart', (e) => {
    if (e.target.closest('.signature-container')) {
      e.preventDefault()
      return false
    }
  })

  // 禁用选择
  document.addEventListener('selectstart', (e) => {
    if (e.target.closest('.signature-container')) {
      e.preventDefault()
      return false
    }
  })

  // 禁用复制
  document.addEventListener('copy', (e) => {
    if (e.target.closest('.signature-container')) {
      e.preventDefault()
      ElMessage.warning('签名受保护，禁止复制')
      return false
    }
  })

  // 禁用F12开发者工具（基础防护）
  document.addEventListener('keydown', (e) => {
    if (e.key === 'F12' || (e.ctrlKey && e.shiftKey && e.key === 'I')) {
      e.preventDefault()
      ElMessage.warning('开发者工具已被禁用')
      return false
    }
  })

  // 禁用截图快捷键
  document.addEventListener('keydown', (e) => {
    if ((e.ctrlKey && e.key === 's') || (e.ctrlKey && e.key === 'p')) {
      if (document.querySelector('.signature-container')) {
        e.preventDefault()
        ElMessage.warning('签名受保护，禁止保存')
        return false
      }
    }
  })
}

// 加载签名数据
function loadSignatureData() {
  try {
    const signatures = JSON.parse(localStorage.getItem(SIGNATURE_STORAGE_KEY) || '{}')
    
    // 只保留SVG格式的签名，删除图片格式
    reviewerSignature.value = signatures.reviewer && signatures.reviewer.includes('<svg') ? signatures.reviewer : ''
    
    // 检查是否已经有保存的检验人员信息
    const settings = JSON.parse(localStorage.getItem(SETTINGS_STORAGE_KEY) || '{}')
    if (settings.inspectorName) {
      // 如果有保存的检验人员信息，使用保存的
      signatureSettings.value.inspectorName = settings.inspectorName
    } else {
      // 如果没有保存的，则重新分配
      signatureSettings.value.inspectorName = getInspectorName()
      // 保存到localStorage
      const newSettings = {
        inspectorName: signatureSettings.value.inspectorName,
        reviewerName: signatureSettings.value.reviewerName
      }
      localStorage.setItem(SETTINGS_STORAGE_KEY, JSON.stringify(newSettings))
    }
    
    // 检验人员签名始终使用文本格式，不保存到localStorage
    inspectorSignature.value = generateInspectorTextSignature()
  } catch (error) {
    console.error('加载签名数据失败:', error)
  }
}

// 生成示例SVG签名
function generateExampleSvg(name) {
  return `<svg width="200" height="60" xmlns="http://www.w3.org/2000/svg">
  <text x="10" y="25" font-family="Arial, Microsoft YaHei, sans-serif" font-size="14" fill="#000" font-weight="normal">${name}</text>
  <line x1="10" y1="30" x2="${Math.max(80, name.length * 8)}" y2="30" stroke="#000" stroke-width="1"/>
</svg>`
}

// 生成检验人员文本签名
function generateInspectorTextSignature() {
  const inspectorName = signatureSettings.value.inspectorName
  return `<svg width="200" height="60" xmlns="http://www.w3.org/2000/svg">
  <text x="10" y="27" font-family="Arial, Microsoft YaHei, sans-serif" font-size="16" fill="#000" font-weight="normal">${inspectorName}</text>
  <line x1="10" y1="35" x2="${Math.max(80, inspectorName.length * 10)}" y2="35" stroke="#000" stroke-width="1"/>
</svg>`
}

// 保存签名数据
function saveSignatureData() {
  try {
    const signatures = {
      inspector: '', // 检验人员签名不保存，始终动态生成
      reviewer: reviewerSignature.value
    }
    localStorage.setItem(SIGNATURE_STORAGE_KEY, JSON.stringify(signatures))
  } catch (error) {
    console.error('保存签名数据失败:', error)
  }
}



// 保存审核人员SVG签名
function saveReviewerSvg() {
  if (!reviewerSvgInput.value.trim()) {
    ElMessage.warning('请输入SVG代码')
    return
  }
  
  // 验证SVG格式
  if (!reviewerSvgInput.value.includes('<svg') || !reviewerSvgInput.value.includes('</svg>')) {
    ElMessage.error('请输入有效的SVG代码')
    return
  }
  
  reviewerSignature.value = reviewerSvgInput.value
  saveSignatureData()
  ElMessage.success('审核人员SVG签名保存成功')
}



// 清空审核人员SVG输入
function clearReviewerSvg() {
  reviewerSvgInput.value = ''
}

// 刷新检验人员签名
function refreshInspectorSignature() {
  signatureSettings.value.inspectorName = getRandomInspectorName()
  inspectorSignature.value = generateInspectorTextSignature()
  
  // 保存新的检验人员信息到localStorage
  const settings = {
    inspectorName: signatureSettings.value.inspectorName,
    reviewerName: signatureSettings.value.reviewerName
  }
  localStorage.setItem(SETTINGS_STORAGE_KEY, JSON.stringify(settings))
  
  ElMessage.success('检验人员已重新分配')
}



// 生成审核人员示例签名
function generateReviewerExample() {
  const exampleSvg = generateExampleSvg(signatureSettings.value.reviewerName)
  reviewerSvgInput.value = exampleSvg
  ElMessage.success('已生成示例SVG签名')
}



// 删除审核人员签名
function removeReviewerSignature() {
  reviewerSignature.value = ''
  reviewerSvgInput.value = ''
  saveSignatureData()
  ElMessage.success('审核人员签名已删除')
}



// 获取签名数据（供外部调用）
function getSignatureData() {
  return {
    inspector: {
      signature: inspectorSignature.value,
      name: signatureSettings.value.inspectorName
    },
    reviewer: {
      signature: reviewerSignature.value,
      name: signatureSettings.value.reviewerName
    }
  }
}

// 暴露方法给父组件
defineExpose({
  getSignatureData,
  loadSignatureData
})

onMounted(() => {
  loadSignatureData()
  setupPrivacyProtection()
})
</script>

<style scoped>
.signature-manage-container {
  padding: 20px;
}

.signature-card {
  max-width: 800px;
  margin: 0 auto;
}

.card-header {
  text-align: center;
  margin-bottom: 30px;
}

.card-title {
  font-size: 24px;
  color: #303133;
  margin: 0 0 8px 0;
}

.card-subtitle {
  font-size: 14px;
  color: #909399;
  margin: 0;
}

.signature-section {
  margin-bottom: 40px;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background: #fafafa;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-title {
  font-size: 18px;
  color: #303133;
  margin: 0;
}

.section-desc {
  font-size: 12px;
  color: #909399;
}

.signature-content {
  display: flex;
  gap: 30px;
  align-items: flex-start;
}

.signature-preview {
  flex: 1;
}

.preview-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
}

.signature-container {
  min-height: 80px;
  border: 2px dashed #dcdfe6;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fff;
  padding: 10px;
}

.signature-svg-container {
  max-width: 100%;
  max-height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.signature-svg {
  max-width: 100%;
  max-height: 100%;
}

.signature-svg svg {
  max-width: 100%;
  max-height: 100%;
}

.no-signature {
  color: #c0c4cc;
  font-size: 14px;
}

.signature-actions {
  flex: 1;
  min-width: 300px;
}

.svg-input-section {
  margin-bottom: 15px;
}

.svg-textarea {
  margin-bottom: 10px;
}

.svg-actions {
  display: flex;
  gap: 10px;
}

.settings-form {
  margin-bottom: 20px;
}

.settings-actions {
  display: flex;
  gap: 10px;
  justify-content: center;
}

.inspector-info {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 6px;
  margin-bottom: 15px;
}

.inspector-info p {
  margin: 5px 0;
  color: #606266;
  font-size: 14px;
}

.inspector-info strong {
  color: #303133;
}

.inspector-actions {
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .signature-content {
    flex-direction: column;
    gap: 20px;
  }
  
  .signature-actions {
    min-width: auto;
  }
  
  .signature-section {
    padding: 15px;
  }
}

/* 签名显示区域样式 */
.signature-display-area {
  display: flex;
  align-items: flex-start;
  gap: 10px;
  width: 100%;
}

.signature-label {
  font-size: 14px;
  color: #303133;
  font-weight: normal;
  white-space: nowrap;
  margin-top: 5px;
}

.signature-content-area {
  position: relative;
  flex: 1;
  min-height: 60px;
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

.signature-svg-container {
  max-width: 100%;
  max-height: 100%;
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

/* SVG签名样式 */
.signature-svg svg {
  max-width: 100%;
  max-height: 100%;
  display: block;
  background: transparent;
}

.signature-svg svg path {
  vector-effect: non-scaling-stroke;
}

.signature-svg svg text {
  font-family: 'Arial', 'Microsoft YaHei', sans-serif;
}

/* 确保SVG背景透明 */
.signature-svg svg rect {
  fill: transparent;
}

.no-signature {
  color: #c0c4cc;
  font-size: 14px;
  position: relative;
  z-index: 2;
}
</style> 